<template>
  <view class="container">
    <view class="video-wrap">
      <video
        id="videoPlayer"
        @play="videoPlayHandle"
        class="vod-video"
        @tap="tapVideo"
        @pause="playPaused"
        @ended="playPaused"
        @timeupdate="timeUpdate"
        @fullscreenchange="fullScreen"
        :poster="currentPoster"
        :src="url"
        @waiting="videoWaiting"
      >
        <!-- 头部信息层 -->
        <cover-view class="video-control" :hidden="controlHidden">
          <!-- 课程标题 -->
          <cover-view class="video-title">{{currentVideoTitle}}</cover-view>
          <!-- 当前清晰度 -->
          <cover-view class="multi" @tap="onSwitchResource">{{definitionStr}}</cover-view>
          <!-- 倍速 -->
          <cover-view class="multi rate" capture-catch:tap="showSwitchRate">x {{currentRate}}</cover-view>
        </cover-view>
        <!-- 清晰度选择 -->
        <cover-view class="multi-list" :class="[multiListShow ? ' active': '' , fullScreenData]">
          <!-- -->
          <cover-view
            class="multi-item"
            :class="[item.definitionFormat === currentDefinition ? ' active ' : ' ']"
            v-for="item in definitionVideoResource"
            @tap="switchDefinition"
            :data-url="item.playURL"
            :data-def="item.definitionFormat"
            :key="Definition"
          >{{computedDef(item.definition)}}</cover-view>
          <cover-view class="close-btn-wrap" :hidden="fullScreenData === ''">
            <cover-view class="close-btn" @tap="closeControl">x</cover-view>
          </cover-view>
        </cover-view>
        <cover-view class="multi-list rate" :class="[rateShow ? ' active': '' , fullScreenData]">
          <cover-view
            v-for="item in ['0.5', '0.8', '1.0', '1.25', '1.5']"
            :key="item"
            class="multi-item rate"
            :class="[item === currentRate ? ' active' : '']"
            :rate="item"
            @tap="switchRate"
          >{{item}}</cover-view>
          <cover-view class="close-btn-wrap" :hidden="fullScreenData === ''">
            <cover-view class="close-btn" @tap="closeControl">x</cover-view>
          </cover-view>
        </cover-view>
      </video>
    </view>

    <scroll-view class="video-list" scroll-y @scrolltolower="loadData">
      <view
        class="video-item"
        :class="[currentVideoId === item.videoId ? ' active' : '']"
        @tap="tapPlay"
        v-for="item in videoList"
        :key="id"
        :vid="item.videoId"
      >
        <view class="cover">
          <image mode="aspectFit" :src="item.coverUrl" />
          <view class="duration">{{item.duration}}</view>
        </view>
        <view class="name">
          <view class="video-title-name">{{item.title}}</view>
          <view class="video-title-name description">{{item.description}}</view>
        </view>
      </view>
      <view class="tips" :hidden="!loadAll">No more</view>
      <view class="tips" :hidden="!loading">loading...</view>
    </scroll-view>
  </view>
</template>

<script>
export default {
  name: "aliplayer",
  components: {},
  props: {
    url: String,
    // 默认视频清晰度，此值是vid对应流的一个清晰度，取值范围：FD（流畅）LD（标清）SD（高清）HD（超清）OD（原画）2K（2K）4K（4K），仅H5支持。
    defaultDefinition: {
      type: String,
      default: "FD"
    },
    definition: {
      type: Array,
      default: ["FD", "LD", "SD", "HD", "OD", "2K", "4K"]
    },
    definitionVideoResource: {
      type: Array,
      default: [
        {
          definition: "FD",
          value: ""
        },
        {
          definition: "LD",
          value: ""
        }
      ]
    }
  },
  data() {
    return {
      page: 1,
      size: 5,
      userInfo: null,
      videoList: [],
      total: 0,
      loading: false,
      loadAll: false,
      currentResource: "",
      multiListShow: false,

      rateShow: false,
      currentRate: "1.0",

      videoPlaying: false,
      controlHidden: false,

      currentTime: 0,

      isSwitchDefinition: false,

      currentVideoId: "",
      currentPoster: "",
      currentVideoTitle: "",
      currentDefinition: this.defaultDefinition,
      isAndroid: false,

      fullScreenData: ""
    };
  },
  created() {},
  mounted() {},
  computed: {
    definitionStr() {
      let def = {
        FD: "流畅",
        LD: "标清",
        SD: "高清",
        HD: "超清",
        OD: "原画",
        "2K": "2K",
        "4K": "4K"
      };
      return def[this.currentDefinition];
    }
  },
  methods: {
    // 视频缓冲触发事件
    videoWaiting() {
      this.controlHidden = true;
    },

    computedDef(definition) {
      return this.definition[definition];
    },

    videoPlayHandle(e) {
      this.videoPlaying = true;

      this.controlHidden = false;
      this.multiListShow = false;
      // 设置倍速播放
      this.videoContext.playbackRate(Number(this.currentRate));
      if (this.isSwitchDefinition) {
        console.log("seek");
        // 跳转到指定位置，单位 s
        this.videoContext.seek(this.currentTime);
        this.isSwitchDefinition = false;
      }
    },

    closeControl() {
      this.setData({
        multiListShow: false,
        rateShow: false
      });
    },
    /**
     * 点击视频触发
     *  修改控制栏的显示与隐藏
     */
    tapVideo(e) {
      console.log(e);
      console.log("tapVideo");
      this.multiListShow = false;
      this.rateShow = false;

      console.log(this.videoPlaying);
      if (this.videoPlaying && !this.fullScreenData) {
        this.controlHidden = !this.controlHidden;
      }
    },
    /**
     * 点击切换清晰度
     */
    onSwitchResource() {
      console.log("switch");
      this.multiListShow = true;
    },

    showSwitchRate(rate) {
      this.setData({
        rateShow: true
      });
    },

    switchRate(e) {
      let dataset = e.currentTarget.dataset;
      let { rate } = dataset;
      console.log(this.videoplaying);
      if (this.videoplaying) {
        this.videoContext.playbackRate(Number(rate));
      }
      this.setData({
        currentRate: rate,
        rateShow: false
      });
    },

    switchDefinition(e) {
      this.data.isSwitchDefinition = true;

      let dataset = e.currentTarget.dataset;
      let { url, def } = dataset;
      this.setData({
        currentResource: url,
        currentDefinition: def,
        multiListShow: false
      });
    },

    onLoad() {
      const res = wx.getSystemInfoSync();
      console.log(res.SDKVersion);

      this.loadData();
      try {
        const res = wx.getSystemInfoSync();

        if (res.system.toLowerCase().indexOf("android") > -1) {
          this.data.isAndroid = true;
        }
      } catch (e) {
        console.log(e);
      }
    },

    onReady() {
      this.videoContext = uni.createVideoContext("videoPlayer", this);
      console.log(this.videoContext);
    },

    onPullDownRefresh() {
      this.setData({
        loadAll: false,
        page: 1,
        total: 0,
        videoList: []
      });
      this.loadData(() => {
        wx.stopPullDownRefresh();
      });
    },

    tapPlay(e) {
      let vid = e.currentTarget.dataset["vid"];
      this.playVideo(vid);
    },

    playVideo(vid) {
      if (!this.videoContext) {
        this.videoContext = wx.createVideoContext("videoPlayer");
      }
      // this.videoContext.stop()
      this.data.videoPlaying = false;
      wx.showLoading({
        title: "加载中...",
        icon: "none"
      });
      getVideoById({
        url: "/vodVideo/getVideoById",
        data: {
          videoId: vid
        }
      })
        .then(({ data }) => {
          wx.hideLoading();
          console.log(data);
          let currentVideoId = vid;
          let currentPoster = data.videoBase.coverURL;
          let currentResource = data.playInfoList[0].playURL;
          let currentVideoTitle = data.videoBase.title;
          let currentVideoResource = data.playInfoList.map(item => {
            item.definitionFormat = this.computedDef(item.definition);
            return item;
          });
          this.setData({
            currentVideoId,
            currentPoster,
            currentVideoTitle,
            currentResource,
            currentVideoResource,
            currentDefinition: currentVideoResource[0].definitionFormat
          });

          // this.videoContext.play()
        })
        .catch(err => {
          wx.hideLoading();
          console.log(err);
          serviceError("获取播放地址失败");
        });
    },

    /**
     *  video 时间改变触发
     */
    timeUpdate(e) {
      let { currentTime } = e.detail;
      this.currentTime = currentTime;
      this.videoplaying = true;
    },

    /**
     * 暂停播放
     */
    playPaused() {
      this.videoplaying = false;
    },

    fullScreen(e) {
      let { fullScreen, direction } = e.detail;
      console.log(e);
      let fullScreenData = "";
      if (fullScreen) {
        fullScreenData = " full-screen " + direction;
        this.setData({ controlHidden: false });
      }
      console.log({ fullScreen, direction });
      this.setData({ fullScreenData });
      console.log(this.data.fullScreenData);
    },

    loadData(cb) {
      if (this.data.loadAll || this.data.loading) {
        return;
      }
      if (this.data.userInfo !== null) {
        this.getVideoList(cb);
      } else {
        getToken({ url: "/user/randomUser" })
          .then(({ data }) => {
            console.log(data);
            this.data.userInfo = data;
            this.getVideoList();
          })
          .catch(err => {
            serviceError("获取token失败");
            console.log(err);
          });
      }
    },
    getVideoList(cb) {
      this.loading = true;
      if (this.data.userInfo === null) {
        reject(new Error("no user"));
      } else {
        let { token } = this.data.userInfo;
        let { page, size } = this.data;
        getVideoList({
          url: "/vod/getRecommendVideoList",
          data: {
            token,
            pageIndex: page,
            pageSize: size
          }
        })
          .then(({ data }) => {
            if (page === 1) {
              this.playVideo(data.videoList[0].videoId);
            }

            this.loading = false;
            let loadAll = false;
            if ((page + 1) * size >= data.total) {
              loadAll = true;
            }
            data.videoList.forEach(
              item => (item.duration = this.getVideoTime(item.duration))
            );
            this.setData({
              loadAll,
              total: data.total,
              page: page + 1,
              videoList: this.data.videoList.concat(data.videoList)
            });
            typeof cb === "function" && cb();
          })
          .catch(err => {
            this.loading = false;
            serviceError("获取视频列表失败");
            typeof cb === "function" && cb();
          });
      }
    },
    getVideoTime(duration) {
      let secondTotal = Math.round(duration);

      let hour = Math.floor(secondTotal / 3600);
      let minute = Math.floor((secondTotal - hour * 3600) / 60);

      let second = secondTotal - hour * 3600 - minute * 60;

      if (minute < 10) {
        minute = "0" + minute;
      }
      if (second < 10) {
        second = "0" + second;
      }
      return hour === 0
        ? minute + ":" + second
        : hour + ":" + minute + ":" + second;
    }
  }
};
</script>

<style scoped lang="scss" src="./index.scss">
</style>
